package com.liwen.kefu.common.result;

import lombok.Data;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @author: Liwen
 * @createTime: 2024/11/9
 * @description:
 */

@Data
public class ResponseResult<T> {

    private int code;
    private boolean success;
    private String message;

    private T data;


    public ResponseResult(CommonCode code) {
        this.code = code.getCode();
        this.message = code.getMessage();
        this.success = code.getSuccess();
    }


    private ResponseResult(CommonCode baseCode, T data) {
        this.code = baseCode.getCode();
        this.success = baseCode.getSuccess();
        this.message = baseCode.getMessage();
        this.data = data;
    }


    /**
     * 不带结果集
     *
     * @param code
     * @return
     */
    public static ResponseResult SUCCESS(CommonCode code) {
        return new ResponseResult(code);
    }

    public static <T> ResponseResult<T> SUCCESS(CommonCode code, T data) {
        return new ResponseResult(code, data);
    }


    /**
     * 错误响应
     *
     * @param code
     * @return
     */
    public static ResponseResult ERROR(CommonCode code) {
        return new ResponseResult(code);
    }

    /**
     * 错误响应带结果集
     *
     * @param code
     * @return
     */
    public static <T> ResponseResult<T> ERROR(CommonCode code, Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw, true));
        String info = sw.toString().replaceAll("\r", "").replaceAll("\t", "").replaceAll("\n", "").replaceAll("tat", "");
        return new ResponseResult(code, info);
    }

    public static <T> ResponseResult<T> ERROR(CommonCode code, T data) {
        return new ResponseResult(code, data);
    }

}
